package com.itranswarp.learnjava.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;


import com.fasterxml.jackson.core.JsonProcessingException;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;


import com.itranswarp.learnjava.bean.User;
import com.itranswarp.learnjava.bean.Role;
import com.itranswarp.learnjava.bean.RolePermission;
import com.itranswarp.learnjava.bean.PageResult;
import com.itranswarp.learnjava.bean.RolePermissionOpt;

import com.itranswarp.learnjava.framework.GetMapping;
import com.itranswarp.learnjava.framework.ModelAndView;
import com.itranswarp.learnjava.framework.PostMapping;

import com.itranswarp.learnjava.utils.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itranswarp.learnjava.dao.RoleDAO;
import com.itranswarp.learnjava.dao.PermissionDAO;

public class RoleController {

    public static void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK); // ✅ 明确设置 200
        PrintWriter pw = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        pw.write(mapper.writeValueAsString(obj));
        pw.flush();
    }

    public static boolean validateUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        return user != null;
    }


    @GetMapping("/roles")
    public ModelAndView doRoles(int page, HttpSession session) throws JsonProcessingException {
        if(!validateUser(session)){
            return new ModelAndView("redirect:/login");
        }
        int offset = page-1;
        RoleDAO roleDAO = new RoleDAO();
        PageResult<Role> result = roleDAO.getAllRoles(Math.max(offset, 0), 10);
        ObjectMapper mapper = new ObjectMapper();
        return new ModelAndView("/roles.html", "result", mapper.writeValueAsString(result));
    }

    @GetMapping("/role_permission")
    public ModelAndView doRolePermission(int roleId, int page, HttpSession session) throws JsonProcessingException {
        if(!validateUser(session)){
            return new ModelAndView("redirect:/login");
        }
        int offset = page-1;
        PageResult<RolePermission> result = PermissionDAO.getPermisionsByRoleId(roleId, Math.max(offset, 0), 10);
        ObjectMapper mapper = new ObjectMapper();
        return new ModelAndView("/role_right.html", "result", mapper.writeValueAsString(result));
    }

    // 移除角色权限
    @PostMapping("/api/removeRolePermission")
    public ModelAndView doRemoveRolePermission(RolePermission bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(401, "未登录", null));
        } else {
            if(RoleDAO.removeRolePermission(bean.id)){
                writeJson(response, new Response<>(200, "", null));
            } else {
                writeJson(response, new Response<>(204, "删除失败", null));
            }
        }
        return null;
    }

    @PostMapping("/api/addRolePermission")
    public ModelAndView doAddRolePermission(RolePermissionOpt bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(401, "未登录", null));
        } else {
            if(RoleDAO.addRolePermission(bean.roleId, bean.permissionId)){
                writeJson(response, new Response<>(200, "", null));
            } else {
                writeJson(response, new Response<>(204, "删除失败", null));
            }
        }
        return null;
    }

    @PostMapping("/api/updateRole")
    public ModelAndView doUpdateRole(Role bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(401, "未登录", null));
        } else {
            if(RoleDAO.updateRole(bean.id, bean.role_name)){
                writeJson(response, new Response<>(200, "", null));
            } else {
                writeJson(response, new Response<>(204, "修改失败", null));
            }
        }
        return null;
    }

    @PostMapping("/api/removeRole")
    public ModelAndView doRemoveRole(Role bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(401, "未登录", null));
        } else {
            if(RoleDAO.removeRole(bean.id)){
                writeJson(response, new Response<>(200, "", null));
            } else {
                writeJson(response, new Response<>(204, "删除失败", null));
            }
        }
        return null;
    }

    @PostMapping("/api/addRole")
    public ModelAndView doAddRole(Role bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(401, "未登录", null));
        } else {
            if(RoleDAO.addRole(bean.role_name, bean.role_code)){
                writeJson(response, new Response<>(200, "", null));
            } else {
                writeJson(response, new Response<>(204, "授权失败", null));
            }
        }
        return null;
    }


}
